14. How Java Loads Classes

How Java Loads Classes

In this section, you'll learn about how Java loads classes, and you'll use a custom class loader to load class byte code.

ND079 JPND C2 L04 A13 How Java Loads Classes

Java Program Lifecycle

Before we get into the details of class loaders, let's brush up on these terms by reviewing the basic lifecycle of developing and executing a Java program.

Basic Lifecycle

  1. You start by writing Java source code, which is human-readable text.
  2. The Java compiler, or the javac command, compiles the source code into bytecode. Bytecode is Java's platform-independent representation of the classes in the program.
  3. The Java launcher, or the java command, starts up the Java Virtual Machine, and loads the bytecode to execute the program.

Why does Java compile to byte code?

SOLUTION: Byte code can execute on any Java Virtual Machine.

Where Java Looks for Bytecode

Class bytecode is stored in files, such as .class files, .jar files, or .zip files. The Java launcher needs to find these files. Here are the different ways the Java launcher looks for them:

  1. Looks in the lhe local file system for the Java Runtime Installation, which contains Bootstrap Classes, like java.lang.Object and java.lang.String. The location of the installation comes from the JAVA_HOME environment variable.
  2. Looks for user-defined classes in the current directory where the java command is running.
  3. Follows the CLASSPATH environment variable.
  4. Follows the -classpath or -jar options passed to the java command on the command-line.

Where does the Java launcher look for Java bytecode when loading user classes?

SOLUTION:
  • The current directory where the Java program is running.
  • Files pointed to by the `CLASSPATH` environment variable.
  • The value of the `-classpath` (or `-cp`) option passed to the `java` command.
  • The value of the `-jar` option passed to the `java` command.

Class Loaders

Every class in the Java Runtime is loaded by a ClassLoader.

The input to a ClassLoader is the name of the class to be loaded, and the output is the Class object representing that class:

The ClassLoader tries to locate the bytecode of the class (similarly to how the Java launcher loads bytecode — described above), and then creates an instance of the corresponding Class object.

Further Reading